from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.good import spu_serializers
from meiduo_admin.my_paginate import MyPageNumberPagination
from django.conf import settings
from fdfs_client.client import Fdfs_client


# 1.spu 管理
class SPUViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = spu_serializers.SPUSerializer
    queryset = SPU.objects.all()

# 2.spu ，brand 品牌获取
class SPUBrandSimpleView(ListAPIView):
    serializer_class = spu_serializers.SPUBrandSimpleSerializer
    queryset = Brand.objects.all()

#3,spu,category分类获取
class SPUCategoryView(ListAPIView):
    serializer_class = spu_serializers.SPUCategorySerializer
    queryset = GoodsCategory.objects.filter(parent__isnull=True)

#4,spu,二级分类,三级分类
class SPUSubsCategoryView(ListAPIView):
    serializer_class = spu_serializers.SPUCategorySerializer

    def get_queryset(self):
        category_id = self.kwargs.get("category_id")
        queryset = GoodsCategory.objects.filter(parent_id=category_id).all()
        return queryset


#5,spu,image上传
class SPUImageUploadView(APIView):

    def post(self,request):
        #1,获取参数
        image = request.FILES.get("image")

        #2,校验参数
        if not image:
            return Response(status=400)

        #3,数据入库(fdfs)
        #3,1 上传图片
        client = Fdfs_client(settings.BASE_CONFIG)
        result = client.upload_by_buffer(image.read())

        #3,2 判断图片是否上传成功
        if result.get("Status") != "Upload successed.":
            return Response(status=400)

        image_url = result.get("Remote file_id")

        #4,返回响应
        return Response({
            "img_url":"%s%s"%(settings.BASE_URL,image_url)
        })